package org.cfx.gift.service.impl;

import com.baomidou.mybatisplus.mapper.Wrapper;
import org.cfx.gift.domain.TenantType;
import org.cfx.gift.mapper.TenantTypeMapper;
import org.cfx.gift.service.ITenantTypeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cfx
 * @since 2023-11-01
 */
//@Service
public class TenantTypeServiceImpl_同步代码块 extends ServiceImpl<TenantTypeMapper, TenantType> implements ITenantTypeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TenantTypeMapper tenantTypeMapper;

    private static final String DATA_IN_REDIS = "data_in_redis";

    /**
     * 新增完后删除缓存
     *
     * @param entity
     * @return
     */
    @Override
    public boolean insert(TenantType entity) {
        boolean flag = super.insert(entity);
        redisTemplate.delete(DATA_IN_REDIS);
        return flag;
    }

    @Override
    public boolean updateById(TenantType entity) {
        boolean flag = super.updateById(entity);
        redisTemplate.delete(DATA_IN_REDIS);
        return flag;
    }

    @Override
    public boolean deleteById(Serializable id) {
        boolean flag = super.deleteById(id);
        redisTemplate.delete(DATA_IN_REDIS);
        return flag;
    }

    @Override
    public List<TenantType> selectList(Wrapper<TenantType> wrapper) {
        //1 先去redis里面查询
        Object o = redisTemplate.opsForValue().get(DATA_IN_REDIS);
        //2 判断是否存在
        if (o != null) {
            // 如果存在就直接返回
            return (List<TenantType>) o;
        }
        //3 不存在就去数据库里查询，并保存缓存
        synchronized (TenantTypeServiceImpl_同步代码块.class) {
            /*
                这里再判断一次，是为了防止第一次缓存中没有，去数据库里查询了。放到了缓存里。
                但是后面排队的请求又要去操作数据的情况
             */
            Object o1 = redisTemplate.opsForValue().get(DATA_IN_REDIS);
            if (o1 != null) {
                return (List<TenantType>) o1;
            }
            List<TenantType> tenantTypes = tenantTypeMapper.selectList(wrapper);
            redisTemplate.opsForValue().set(DATA_IN_REDIS, tenantTypes);
            return tenantTypes;
        }
    }
}
